package com.sanhuo.security.service;

import com.sanhuo.security.dao.UserTokenMapper;
import com.sanhuo.security.entity.User;
import com.sanhuo.security.entity.UserToken;
import com.sanhuo.security.uitls.UserHolder;
import com.sanhuo.triild.Basic.BaseMapper;
import com.sanhuo.triild.Basic.BaseService;
import com.sanhuo.triild.annotation.MapperWire;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.basic.Dateutil;
import com.sanhuo.utils.basic.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserTokenService extends BaseService<UserToken> {
    @MapperWire
    private UserTokenMapper userTokenMapper;
    @Autowired
    private UserService userService;

    @Override
    public BaseMapper<UserToken> getBaseMapper() {
        return userTokenMapper;
    }

    public UserToken updateToken(String id) {
        User user = userService.findById(id);
        UserToken userToken = userTokenMapper.findByUserId(user.getId());
        String token = StringUtil.token();
        if (BeanUtil.isNull(userToken)) {
            userToken = new UserToken();
            userToken.setId(StringUtil.UUID());
            userToken.setUserId(user.getId());
            userToken.setTokenStr(token);
            userToken.setTime(Dateutil.addDay(7));
            userTokenMapper.save(userToken);

        } else {
            UserHolder.remove(userToken.getTokenStr());
            userToken.setTokenStr(token);
            userToken.setTime(Dateutil.addDay(7));
            userTokenMapper.update(userToken);

        }

        return userToken;
    }

    public User findUserByToken(String token_str) {
        UserToken token = userTokenMapper.findByToken(token_str);
        User user;
        if (BeanUtil.isNotNull(token)) {
            user = userService.findById(token.getUserId());
            return user;
        }
        return null;
    }


}
